package cn.jee.jsp;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/showClazzes")
public class ShowClazzesServlet extends HttpServlet {
  String driver = "org.hsqldb.jdbc.JDBCDriver";
  String url = "jdbc:hsqldb:hsql://localhost/";
  String user = "sa";
  String pass = "";
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doPost(req,resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //List String[]
    List<String[]> res=new ArrayList<>();
    //查询 select * from clazz
    try{
      Class.forName(driver);
      String sql="select * from clazz";
      try(Connection con=DriverManager.getConnection(url,user,pass);
      PreparedStatement pstmt=con.prepareStatement(sql);
      ResultSet rs=pstmt.executeQuery();
      ){
        //遍历
        while(rs.next()){
          String[] row=new String[2];
          row[0]=rs.getString("id");
          row[1]=rs.getString("name");
          res.add(row);
        }
      }
    }catch(Exception ex){
      throw new ServletException(ex);
    }
    //放在session
    HttpSession sesssion=req.getSession();
    sesssion.setAttribute("clazzes",res);
    //重定向
    resp.sendRedirect(req.getContextPath()+"/clazz_list.jsp");
  }
}
